package app.rpc.remote.impl;

public class RemoteUrl {

	public static final String DEFAULT_PROTOCOL = "ro";

	private String protocol = DEFAULT_PROTOCOL;
	private String hostName = "localhost";
	private int port = 9000;
	private String path = "/";

	public RemoteUrl() {
	}

	/**
	 * 
	 * @param url
	 *            连接字符串 [protocol:]hostname[:port][/path]
	 * @param username
	 * @param password
	 */
	public RemoteUrl(String url) {
		parse(url);
	}
	
	public void parse(String url) {
		int ipro = url.indexOf(":");
		int ipath = url.indexOf("/");
		if (ipro != -1) {
			int iport = url.indexOf(":", ipro + 1);
			if (ipath != -1 && ipro > ipath)
				ipro = -1;
			if (ipath != -1 && iport > ipath)
				iport = -1;
			if (ipro != -1&&iport!=-1){// ro:localhost:6000/rpc
				protocol = url.substring(0, ipro);
				hostName = url.substring(ipro+1,iport);
				port = Integer.parseInt(url.substring(iport+1, ipath != -1 ? ipath : url.length()));
			} else if (ipro != -1) {
				if(url.matches("([A-Za-z]+):.+(/.+)?")){// ro:localhost/rpc 
					protocol = url.substring(0, ipro);
					hostName = url.substring(ipro+1,ipath!=-1?ipath:url.length());
				}
				if(url.matches(".+:\\d+(/.+)?")){ // localhost:60/rpc  127.0.0.1:60/rpc
					protocol = "ro";
					hostName = url.substring(0,ipro);
					port = Integer.parseInt(url.substring(ipro+1,ipath!=-1?ipath:url.length()));
				}
			}
		}else{ // localhost  或 localhost/rpc
			hostName = url.substring(0,ipath!=-1?ipath:url.length());
		}
		if (ipath != -1) {
			path = url.substring(ipath);
		}
		
	}

	public String getProtocol() {
		return protocol;
	}

	public void setProtocol(String protocol) {
		this.protocol = protocol;
	}

	public String getHostName() {
		return hostName;
	}

	public void setHostName(String hostname) {
		this.hostName = hostname;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getServerAddress() {
		return this.hostName + ":" + this.port;
	}

	@Override
	public String toString() {
		return protocol + ":" + hostName + ":" + port + path;
	}

	private String adress;

	public String getDeployHost() {
		if (adress == null)
			adress = getHostName() + "-" + getPort();
		return adress;
	}

	public static void main(String[] args) {
		RemoteUrl url = new RemoteUrl("ro:localhost");
		System.out.println(url);
	}
}
